package lesson.c5;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileOperation {
	
	public void testFile2(){
		//FileInputStream和FileReader的关键区别在于：FileReader用于读取字符流，而FileInputStream用来读取原始字节流。
		// 例1 – 使用FileInputStream 读取文件内容
        try (FileInputStream fis = new FileInputStream("./assets/data.txt")) {
            int data = fis.read();
            while (data != -1) {
                System.out.print((char)data);
                data = fis.read();
            }
        } catch (IOException e) {
            System.out.println("Failed to read binary data from File");
            e.printStackTrace();
        }
        
        System.out.println("\n--------\n");
 
        // 例2 – Java中使用FileReader 读取文件数据
        try (FileReader reader = new FileReader("./assets/data.txt")) {
            int character = reader.read();
            while (character != -1) {
                System.out.print((char)character);
                character = reader.read();
            }
        } catch (IOException io) {
            System.out.println("Failed to read character data from File");
            io.printStackTrace();
        }
	}
	public void testFile(){
		try{
		    byte bWrite [] = {65,66,67,68,69};
		    //OutputStream os = new FileOutputStream("./data/test.txt");
		    File f = new File("./data/test.txt");
		    OutputStream os = new FileOutputStream(f);
		    for(int x=0; x < bWrite.length ; x++){
		      os.write( bWrite[x] ); // writes the bytes
		    }
		    os.close();
		 
		    InputStream is = new FileInputStream("./data/test.txt");
		    int size = is.available();
		 
		    for(int i=0; i< size; i++){
		      System.out.print((char)is.read() + "  ");
		    }
		    is.close();
	    }catch(FileNotFoundException e){
	        e.printStackTrace();
	    }catch(IOException e){
	    	e.printStackTrace();
	    }finally{
	    	//int a = 1/0;
	    }
	}
	
	public void testException(){
		try {
			int a = 1/0;
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
	
	public static void main(String[] args) {
		char c ='中';
		
		System.out.println(c);
		FileOperation a = new FileOperation();
		a.testFile2();
	}
}
